<!-- 实时成交 -->
<template>
  <view>
    <view class="top">
      <view class="second">
        <view class="secondLeft">
          <view :class="[_isRFD(coinPriceInfo.open, coinPriceInfo.close, 'buy', 'rise'), ' fw-num']">
            {{ coinPriceInfo.close }}
          </view>
          <view
            :class="[
              _isRFD(coinPriceInfo.openPrice, coinPriceInfo.close, 'buy', 'rise'),
              ' rfd-sign secondLeftB fw-num'
            ]"
          >
            {{ coinPriceInfo.priceChangePercent }}%
          </view>
        </view>
        <view class="secondRight">
          <view class="secondItem">
            <!-- 高 -->
            <view class="itemL">{{ _t18(`k_hight`, ['ebc']) }}</view>
            <view class="itemR fw-num">{{ priceFormat(coinPriceInfo.high24) }}</view>
          </view>
          <view class="secondItem">
            <!-- 低 -->
            <view class="itemL">{{ _t18(`k_low`, ['ebc']) }}</view>
            <view class="itemR fw-num">{{ priceFormat(coinPriceInfo.low24) }}</view>
          </view>
          <view class="secondItem">
            <!-- 量 -->
            <view class="itemL">{{ _t18(`k_quantity`) }}</view>
            <view class="itemR fw-num">{{ countFormat(coinPriceInfo.volume24) }}</view>
          </view>
        </view>
      </view>
    </view>
    <!-- K线 -->
    <Candlestick v-if="coinInfo.coin" :coinInfo="coinInfo" type="detail"></Candlestick>

    <view class="line"></view>
    <!-- 成交/深度图 -->
    <view class="entrust">
      <view class="entrustL">
        <!-- 实时成交 -->
        <view class="entrustItem hightItem">{{ _t18(`real_time_transaction`) }}</view>
        <!-- <view
        :class="currentEntruset ? 'entrustItem hightItem' : 'entrustItem'"
        @click="switchingEntrust"
      >
        深度图
      </view> -->
      </view>
    </view>
    <!-- 成交列表 -->
    <DealList v-if="coinInfo.coin" :coinInfo="coinInfo" :rows="20"></DealList>
    <!-- 左侧 -->
    <PublicPopup
      :show="showOverlay"
      :direction="`left`"
      @handelClose="handelClose"
      :height="`100%`"
      :width="`80%`"
      :showHeader="false"
      :empty="false"
    >
      <template #emptyContentCustomize>
        <LeftSide @linkTo="linkTo" @close="handelClose"></LeftSide>
      </template>
    </PublicPopup>
  </view>
</template>

<script setup>
import Candlestick from './components/common/candlestick.vue'
import DealList from './components/common/dealList.vue'
import PublicPopup from '@/components/Popup/public.vue'
import LeftSide from './components/common/leftSide.vue'
import { countFormat, priceFormat } from '@/utils/decimal'
import { useMainStore } from '@/store/index'
import { useTradeStore } from '@/store/trade'
import { useRoute } from 'vue-router'
import { computed, watch, onMounted, onUnmounted } from 'vue'
import spontaneousCoinService from '@/utils/spontaneousCoinPolling'
import { getSpontaneousCoinPriceApi } from '@/api/spontaneous'

const mainStore = useMainStore()
const tradeStore = useTradeStore()
const $route = useRoute()

// 左侧导航
const showOverlay = ref(false)
const showLeft = () => {
  showOverlay.value = true
}
const handelClose = () => {
  showOverlay.value = false
}

// 成交/深度图
const currentEntruset = ref(false) // 成交/深度图状态
// 成交/深度图切换
const switchingEntrust = () => {
  currentEntruset.value = !currentEntruset.value
}

const coinInfo = computed(() => {
  let temp = {}
  if (Number($route.query.type) == 2) {
    if ($route.query.symbol && tradeStore.contractCoinList.length > 0) {
      temp =
        tradeStore.contractCoinList.filter((obj) => {
          return obj.coin === $route.query.symbol
        })[0] || tradeStore.contractCoinList[0]
    } else if (tradeStore.contractCoinList.length > 0) {
      temp = tradeStore.contractCoinList[0]
    }
  } else {
    if ($route.query.symbol && tradeStore.spotCoinList.length > 0) {
      temp =
        tradeStore.spotCoinList.filter((obj) => {
          return obj.coin === $route.query.symbol
        })[0] || tradeStore.spotCoinList[0]
    } else if (tradeStore.spotCoinList.length > 0) {
      temp = tradeStore.spotCoinList[0]
    }
  }

  return temp
})

const getHeader = () => {}

const coinPriceInfo = computed(() => {
  return coinInfo.value.coin ? tradeStore.allCoinPriceInfo[coinInfo.value.coin] || {} : {}
})

/**
 * 检查是否为币
 * @param {Object} coin 币种信息
 * @returns {boolean}
 */
const isSpontaneousCoin = (coin) => {
  if (!coin) {
    return false
  }
  
  // 多种判断条件，确保准确识别币
  const isSpontaneous = (
    coin.market === 'spontaneous' || 
    coin.spontaneousCoin === true ||
    coin.spontaneousCoin === 1 ||
    coin.spontaneousCoin === '1' ||
    coin.coinType === 'spontaneous' ||
    coin.type === 'spontaneous'
  )
  
  console.log(`详情页币种 ${coin.coin} 币判断:`, {
    market: coin.market,
    spontaneousCoin: coin.spontaneousCoin,
    coinType: coin.coinType,
    type: coin.type,
    isSpontaneous
  })
  
  return isSpontaneous
}

/**
 * 币种价格更新回调
 * @param {Object} priceData 价格数据
 */
const onSpontaneousCoinPriceUpdate = (priceData) => {

  // 更新tradeStore中的价格信息
  if (priceData && coinInfo.value.coin) {
    const currentPriceInfo = tradeStore.allCoinPriceInfo[coinInfo.value.coin] || {}
    
    // 更新价格信息
    const updatedPriceInfo = {
      ...currentPriceInfo,
      close: priceData.close || priceData.price || currentPriceInfo.close,
      high24: priceData.high || priceData.high24 || currentPriceInfo.high24,
      low24: priceData.low || priceData.low24 || currentPriceInfo.low24,
      volume24: priceData.volume || priceData.volume24 || currentPriceInfo.volume24,
      priceChangePercent: priceData.changePercent || priceData.priceChangePercent || currentPriceInfo.priceChangePercent,
      openPrice: priceData.open || priceData.openPrice || currentPriceInfo.openPrice
    }
    
    // 更新store
    tradeStore.updateCoinPriceInfo(coinInfo.value.coin, updatedPriceInfo)
    
  }
}

/**
 * 获取币种价格（单次请求）
 */
const getSpontaneousCoinPrice = async () => {
  if (isSpontaneousCoin(coinInfo.value)) {
    try {
      console.log(`获取币种 ${coinInfo.value.coin} 价格`)
      await spontaneousCoinService.getSpontaneousCoinPrice(coinInfo.value.coin, onSpontaneousCoinPriceUpdate)
    } catch (error) {
      console.error(`获取币种 ${coinInfo.value.coin} 价格失败:`, error)
    }
  }
}

/**
 * 清除币种请求状态
 */
const clearSpontaneousCoinRequestStatus = () => {
  if (coinInfo.value.coin) {
    spontaneousCoinService.clearRequestStatus(coinInfo.value.coin)
  }
}

/** 更换当前路由信息 */
const linkTo = (item, type) => {
  $route.query.symbol = item
  $route.query.type = type||$route.query.type
  showOverlay.value = false
  getHeader()
}

// 监听币种列表加载状态
watch(
  () => [tradeStore.spotCoinList.length, tradeStore.contractCoinList.length],
  () => {
    // 当币种列表加载完成后，重新计算 coinInfo
    if (coinInfo.value?.coin) {
      console.log('币种列表已加载，当前币种:', coinInfo.value.coin)
      // 如果是币，获取价格
      if (isSpontaneousCoin(coinInfo.value)) {
        getSpontaneousCoinPrice()
      }
    }
  },
  { immediate: true }
)

// 监听币种变化
watch(
  () => coinInfo.value?.coin,
  (newCoin, oldCoin) => {
    console.log('币种切换:', oldCoin, '->', newCoin)
    
    // 清除旧币种的请求状态
    if (oldCoin) {
      spontaneousCoinService.clearRequestStatus(oldCoin)
      tradeStore.setCurrentCoinList(oldCoin, 'remove')
    }
    
    // 处理新币种
    if (newCoin) {
      tradeStore.setCurrentCoinList(newCoin)
      
      // 如果是币，获取价格
      if (isSpontaneousCoin(coinInfo.value)) {
        getSpontaneousCoinPrice()
      }
    }
  },
  { immediate: true }
)

onMounted(() => {
  mainStore.setTradeFlag(mainStore.tradeFlag + mainStore.isOption)
  getHeader()
  console.log(coinInfo.value)
  // 如果是币，获取价格
  if (coinInfo.value?.coin && isSpontaneousCoin(coinInfo.value)) {
    getSpontaneousCoinPrice()
  }
})

onUnmounted(() => {
  // 清除请求状态
  clearSpontaneousCoinRequestStatus()
  if (coinInfo.value?.coin) {
    tradeStore.setCurrentCoinList(coinInfo.value.coin, 'remove')
  }
})
</script>

<style lang="scss" scoped>
header {
  width: 100%;
  display: flex;
  height: 60px;
  padding: 0 15px;
  align-items: center;
  background-color: var(--ex-default-background-color);
  z-index: 99;
  justify-content: space-between;
  border-bottom: 1px solid var(--ex-border-color);
  position: relative;
  .leftImg {
    width: 16px;
    height: 12px;
  }
  .right {
    .senLeftImg {
      width: 24px;
      height: 24px;
      margin-left: 10px;
      display: none;
    }
    .central {
      font-size: 16px;
      color: var(--ex-default-font-color);
      position: absolute;
      top: 50%;
      left: 28%;
      transform: translate(-50%, -50%);
      display: flex;
      align-items: center;
      .firLeftImg {
        width: 17px;
        height: 14px;
        margin-right: 10px;
      }
    }
  }
}
.top {
  background-color: var(--ex-default-background-color);
  .second {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 15px;
    .secondLeft {
		// display:block;
      font-size: 36px !important;
      font-weight: bold;
      color: var(--ex-font-color10);
	  display:flex;
	  flex-direction: column;
	  
      > * {
        transition: 0.3s;
      }
      .secondLeftB {
        font-size: 14px;
        margin-top: 5px;
      }
    }
    .secondRight {
      .secondItem {
        display: flex;
        align-items: center;
        padding: 6px 0;
        font-size: 14px;
        .itemL {
          color: var(--ex-passive-font-color);
          margin-right: 10px;
        }
        .itemR {
          color: var(--ex-default-font-color);
        }
      }
    }
  }
}
.line {
  height: 5px;
  background: var(--ex-div-bgColor10);
}
.entrust {
  height: 50px;
  display: flex;
  padding: 0 15px;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid var(--ex-border-color);
  .entrustL {
    font-size: 14px;
    color: var(--ex-default-font-color);
    display: flex;
    .entrustItem {
      margin-right: 30px;
    }
    .hightItem {
      font-weight: bold;
      // color: var(--ex-font-color9);
    }
  }
}
</style>
